/*
 * CCasterChannel.cpp
 *
 *  Created on: 2016年4月6日
 *      Author: terry
 */

#include "CCasterChannel.h"
#include "CUdpMediaCaster.h"
#include "RtpCaster.h"
#include "CTcpMediaCaster.h"
#include "CLog.h"


namespace av
{

CCasterChannel::CCasterChannel():
		m_codec(),
		m_clockRate(),
		m_outPort(),
		m_ssrc(),
		m_payload(),
		m_udpCaster()
{
	m_udpCaster.reset(new CUdpMediaCaster());
	m_tcpCaster.reset(new CTcpMediaCaster());
}

CCasterChannel::~CCasterChannel()
{
	close();
}

void CCasterChannel::close()
{
	m_clockRate = 0;

	m_udpCaster->close();
	m_tcpCaster->close();

	CLog::debug("CCasterChannel. close.\n");
}

bool CCasterChannel::isOpen()
{
	return (m_clockRate > 0) && m_udpCaster->isOpen();
}

int CCasterChannel::open(int codec, int clockRate, int outPort, int ssrc)
{
	CLog::debug("CCasterChannel::open. codec:%d, rate:%d, outPort:%d\n", codec, clockRate, outPort);

	m_codec = codec;
	m_clockRate = clockRate;
	m_outPort = outPort;
	m_ssrc = ssrc;

	m_payload = 96;

	m_udpCaster->open("0.0.0.0", outPort, m_codec, m_clockRate, m_payload, m_ssrc);

	int rc = m_tcpCaster->open("0.0.0.0", outPort, m_codec, m_clockRate, m_payload, m_ssrc);

	return rc;
}

int CCasterChannel::addTarget(int protocol, const char* ip, int port)
{
	if ((ip == NULL) || (strlen(ip) <=0) || (port <= 0))
	{
		return EINVAL;
	}

	CLog::debug("CCasterChannel. addTarget. protocol:%d, %s:%d\n", protocol, ip, port);

	int rc = 0;
	if (protocol == kProtocolUdp)
	{
		m_udpCaster->addTarget(ip, port);
	}
	else
	{
		m_tcpCaster->addTarget(ip, port);
	}

	return rc;
}

int CCasterChannel::removeTarget(int protocol, const char* ip, int port)
{
	CLog::debug("CCasterChannel. removeTarget. protocol:%d, %s:%d\n", protocol, ip, port);

	if (protocol == kProtocolUdp)
	{
		m_udpCaster->removeTarget(ip, port);
	}
	else
	{
		m_tcpCaster->removeTarget(ip, port);
	}
	return 0;
}

int CCasterChannel::removeAllTarget(int protocol)
{
	CLog::debug("CCasterChannel. removeAllTarget. protocol:%d\n", protocol);

	if (protocol == kProtocolUdp)
	{
		m_udpCaster->removeAllTarget();
	}
	else
	{
		m_tcpCaster->removeAllTarget();
	}

	return 0;
}

int CCasterChannel::write(MediaPacketPtr& pkt)
{
    if (!pkt)
    {
        return EINVAL;
    }

    fireMediaPacket(pkt);

    return 0;
}

void CCasterChannel::fireMediaPacket(MediaPacketPtr& pkt)
{
	m_udpCaster->onMediaPacket(pkt);

	m_tcpCaster->onMediaPacket(pkt);
}




} /* namespace av */
